package cn.exrick.xboot.modules.ApprovalInfo.utils;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.SpringUtils;
import cn.exrick.xboot.common.webSocket.WebSocketServer;
import cn.exrick.xboot.modules.ApprovalInfo.entity.ApprovalInfo;
import cn.exrick.xboot.modules.ApprovalInfo.service.IApprovalInfoService;
import cn.exrick.xboot.modules.ApprovalInfo.serviceimpl.IApprovalInfoServiceImpl;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.entity.UserRole;
import cn.exrick.xboot.modules.base.service.mybatis.IUserRoleService;
import cn.exrick.xboot.modules.base.serviceimpl.mybatis.IUserRoleServiceImpl;
import cn.exrick.xboot.modules.subsystemNews.entity.SubsystemNews;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApprovalInfoUtils {

   /* @Autowired
    public IUserRoleService iUserRoleService;*/

  // private  IApprovalInfoService iApprovalInfoService = (IApprovalInfoService)SpringUtils.getBean("IApprovalInfoServiceImpl");

   /**
     * njp
     * 1.在超级管理员提交审批请求后使用websocket向pc端推送新审批数据
     * 2.使用极光推送向APP推送新审批数据
     *
     * @return
     */
    public  boolean sendApprovalInfo(ApprovalInfo approvalInfo) {
        IApprovalInfoService iApprovalInfoService = (IApprovalInfoService)SpringUtils.getBean("IApprovalInfoServiceImpl");
         ApprovalInfoUtils approvalInfoUtils=new  ApprovalInfoUtils();
        //查询出所有的审批员
        List<User> approvalUsers =approvalInfoUtils.getAPPROVAL();
        log.info("共有"+approvalUsers.size()+"个审批员");
        for (User approvalUser : approvalUsers) {
            String username=approvalUser.getUsername();
            log.info("审批员username："+username);
            //1.使用websocket向pc端推送新审批数据
            Map map=new HashMap();
            map.put(CommonConstant.APPROVAL_UPDATE,true);
            map.put(CommonConstant.ApprovalInfo,approvalInfo);
            try{
                WebSocketServer.sendToUser(map,username);
                //2.使用极光推送向APP推送新审批数据
                //等待app开发
                iApprovalInfoService.sendApprovalInfoToAPP(username);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 审批结束后,后台通过长连接向前端发送审批结果
     * @return
     */
    public  Boolean sendApprovalResult(ApprovalInfo approvalInfo){
        try{
            IApprovalInfoService iApprovalInfoService = (IApprovalInfoService)SpringUtils.getBean("IApprovalInfoServiceImpl");
        boolean flag=false;
        //String message
    //1.通过id查询该条数据的信息，获取审批数据的提交人（adminCode）
        //IApprovalInfoService iApprovalInfoService = (IApprovalInfoService)SpringUtils.getBean("IApprovalInfoServiceImpl");
        ApprovalInfo appInfo = iApprovalInfoService.getById(approvalInfo.getId());
        String message="success";
        if(CommonConstant.APPROVAL_AGREE==approvalInfo.getApprovalStatus()){
            flag=true;
            message="审批通过";
        } else if(CommonConstant.APPROVAL_DISAGREE==approvalInfo.getApprovalStatus()){
            flag=false;
            message="审批驳回";
        } else if(CommonConstant.APPROVAL_TIMEOUT==approvalInfo.getApprovalStatus()){
            flag=false;
            message="审批超时";
        }
        //将审批登录的长连接返回修改为json 数据
         /* Map map=new HashMap();
         map.put(CommonConstant.APPROVAL_RESULT,flag);//ApprovalResult*/
        JSONObject jsonObject = javaToJSON(appInfo, flag, "200", message);

            WebSocketServer.sendToUser(jsonObject,appInfo.getAdminCode());

        }catch (Exception e){
            e.printStackTrace();
        }

        return true;
    }

    /**
     * add njp 20190830按时间给集合排序 begin
     * @param list
     * @return
     */
    public  List<ApprovalInfo> bubbleSortForTime(List<ApprovalInfo> list){
        int count=0;
        for (int j = 0; j < list.size(); j++) {
            int flag=0;
            for(int i=1;i<list.size();i++){
                count=count+1;
                //按时间倒序排序
                if(list.get(i-1).getCreateTime().before(list.get(i).getCreateTime())){
                    //按时间正序排序
                    //if(list.get(i-1).getCreateTime().after(list.get(i).getCreateTime())){
                    flag=1;
                    ApprovalInfo sub=null;
                    sub=list.get(i-1);
                    list.set((i-1),list.get(i));
                    list.set(i, sub);
                }
            }
            if(flag==0){
                break;
            }
        }
        log.info("cycles:"+count);
        return list;
    }
    /**
     * add njp 20190830按时间给集合排序 end
     */

    //查询出所有的审批员
  public   List<User> getAPPROVAL() {

      IUserRoleServiceImpl iUserRoleServiceImpl = (IUserRoleServiceImpl)SpringUtils.getBean("IUserRoleServiceImpl");
      List<User> userList = iUserRoleServiceImpl.findUsernamesByRoleId(CommonConstant.APPROVAL_ROLRID);
        return userList;
    }

public  void updateStatus(){
    IApprovalInfoService iApprovalInfoService = (IApprovalInfoService)SpringUtils.getBean("IApprovalInfoServiceImpl");


    //1.查询出所有待审批数据并将其修改成超时不可用状态
    ApprovalInfo approvalInfo=new ApprovalInfo();
    approvalInfo.setNowTime(new Date());
    approvalInfo.setApprovalStatus(CommonConstant.APPROVAL_INIT);//3:待审批
    List<ApprovalInfo> approvalInfos = iApprovalInfoService.selectApprovalInfo(approvalInfo);
    //2.将状态修改为超时不可用
    for (ApprovalInfo info : approvalInfos) {
        log.info("将状态修改为超时不可用");
        info.setApprovalStatus(CommonConstant.APPROVAL_TIMEOUT);
        iApprovalInfoService.saveOrUpdate(info);
    }

}

public  JSONObject javaToJSON(ApprovalInfo approvalInfo,Boolean flag,String code,String message) {

      if(flag==null){
          flag=true;
      } /*else {
          if(flag){
              code="200";
          }
      }*/
      if(code==null){
          code="200";
      }
      if(message==null){
          message="success";
      }
    System.out.println("java代码封装为json字符串");
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("success",flag);
    jsonObj.put("code", code);
    jsonObj.put("message", message);
    jsonObj.put("result", approvalInfo);
    jsonObj.put(CommonConstant.APPROVAL_UPDATE, true);
    System.out.println("java--->json \n" + jsonObj.toString());
    return jsonObj;
  }





}
